package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.mapper.RoleMapper;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service(interfaceClass = RoleService.class)
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;


    /**
     * 新增角色
     * @param menusIds
     * @param role
     */
    @Override
    public void addRole(Integer[] menusIds, Role role) {
        //新增检查组
        roleMapper.addRole(role);

        //在检查组和检查项中间表中插入数据
        setRoleAndMenus(menusIds,role.getId());
    }

    private void setRoleAndMenus(Integer[] menusIds, Integer id) {
        if (menusIds!=null && menusIds.length>0){
            roleMapper.setRoleAndMenu(menusIds,id);
        }
    }


    /**
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {

        //定义页面大小和当前页的页码
        PageHelper.startPage(currentPage,pageSize);

        //条件查询数据
        List<Role> roleList = roleMapper.findByCondition(queryString);

        //将数据进行包装
        PageInfo pageInfo = new PageInfo<Role>(roleList);

        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }


    /**
     * 删除
     * @param id
     */
    @Override
    public void deleteRoleById(Integer id) {

        //判断删除的角色是否

        //查询当前角色有没有被用户引用
        Integer count = roleMapper.findCountById(id);
        if (count>0){
            //如果被用户引用了，就抛出异常，提示错误信息
            throw  new RuntimeException(MessageConstant.CHECKGROUP_IS_QUOTED);
        }

        //删除角色和菜单的中间表数据
        roleMapper.deleteAssocation(id);

        //删除角色
        roleMapper.deleteById(id);
    }


    /**
     * 编辑角色
     * @param menusIds
     * @param role
     */
    @Override
    public void editRole(Integer[] menusIds, Role role) {
        //删除表关系
        roleMapper.deleteAssocation(role.getId());

        roleMapper.editRole(role);

        roleMapper.setRoleMenus(role.getId(),menusIds);

    }

    /*
     * @Author: hyy
     * @Description:
     * @Date: 22:10 2020/6/30
     * @param: null
     * @return:
     * @Version: 1.0
     */
    @Override
    public List<Role> findAll() {
        return roleMapper.findAll();
    }
}
